using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Criterion;
using SinBiota.Model.Entities;
using SinBiota.Model.Exceptions;
using SinBiota.Model.Persistence.Repositories.Interfaces;


namespace SinBiota.Model.Persistence.Repositories.Implementation
{
    public class TaxonRepository : RepositoryAbstract<Taxon, int>, ITaxonRepository
    {
        public TaxonRepository(ISession session)
            : base(session)
        {
        }
        public IList<Taxon> FindAncestors(Taxon taxon)
        {
            var list = new List<Taxon>();
            while (taxon != null && taxon.Parent != null && taxon != taxon.Parent)
            {
                list.Insert(0,taxon.Parent);
                taxon = taxon.Parent;
            }
            return list;
        }

        public IList<Taxon> FindAllRootNodes()
        {
            try
            {
                var criteria = Session.CreateCriteria(typeof(Taxon))
                    .Add(Restrictions.IsNull("Parent"));
                return criteria.List<Taxon>();
            }
            catch (HibernateException exception)
            {
                throw new PersistenceException(exception.Message, exception);
            }            
        }

        public IList<Taxon> FindChildren(Taxon taxon)
        {
            try
            {
                var criteria = Session.CreateCriteria(typeof(Taxon))
                    .Add(Restrictions.Eq("Parent", taxon));
                return criteria.List<Taxon>();
            }
            catch (HibernateException exception)
            {
                throw new PersistenceException(exception.Message, exception);
            }
        }
    }
}